<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>搜索</title>
  <script src="https://unpkg.com/vue@2.6.14/dist/vue.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <!-- 引入 axios -->
  <script src="config.js" ></script>

   <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 20px;
      background-color: #f5f5f5;
    }
    .search-container {
      max-width: 800px;
      margin: 0 auto;
    }
    .search-box {
      margin-bottom: 20px;
    }
    .search-box input {
      width: 100%;
      padding: 10px;
      font-size: 16px;
      border: 1px solid #ddd;
      border-radius: 4px;
    }
    .search-box button {
      margin-left: 10px;
      padding: 10px 20px;
      background-color: #1890ff;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
    .cart-link {
      margin-bottom: 20px;
      text-align: right;
    }
    .cart-link a {
      color: #1890ff;
      text-decoration: none;
    }
    .cart-link a:hover {
      text-decoration: underline;
    }
    .product-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 20px;
    }
    .product-item {
      background: white;
      padding: 15px;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      text-align: center;
    }

    .product-item h3 {
      margin: 10px 0;
      font-size: 16px;
      color: #333;
    }
    .product-item p {
      margin: 5px 0;
      color: #666;
    }
    .product-item button {
      padding: 8px 16px;
      margin: 5px;
      border: none;
      border-radius: 4px;
      background-color: #1890ff;
      color: white;
      cursor: pointer;
    }
    .product-item button:hover {
      opacity: 0.9;
    }
    .quantity-control {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 10px 0;
    }
    .quantity-control button {
      padding: 5px 10px;
      background-color: #787878;
      border: 1px solid #ddd;
      cursor: pointer;
    }
    .quantity-control input {
      width: 50px;
      text-align: center;
      margin: 0 5px;
      padding: 5px;
      border: 1px solid #ddd;
      border-radius: 4px;
    }
  </style>
</head>
<body>
  <div id="app" class="search-container">
    <div class="search-box">
      <input type="text" v-model="keyword" placeholder="请输入商品名称">
      <button @click="searchProducts">搜索</button>
    </div>
    <div class="cart-link">
      <a href="cart.html">查看购物车 </a>
    </div>
    <div class="product-list">
      <div v-for="product in products" :key="product.productId" class="product-item">
        <h3>{{ product.name }}</h3>
        <p>价格：￥{{ product.price }}</p>
        <p>库存：{{ product.stock }}</p>
        <div class="quantity-control">
          <button @click="decreaseQuantity(product)">-</button>
          <input type="number" v-model="product.quantity" min="1" :max="product.stock">
          <button @click="increaseQuantity(product)">+</button>
        </div>
        <button @click="addToCart(product.productId, product.quantity)">加入购物车</button>
        <button @click="toggleLike(product.productId)">点赞</button>
      </div>
    </div>
  </div>

  <script>
    new Vue({
      el: '#app',
      data() {
        return {
          keyword: '',
          products: [],
        }
      },
      created() {
        this.fetchAllProducts();
      },
      methods: {
        async fetchAllProducts() {
          try {
            const response = await axiosInstance.get('/product/list');
            this.products = response.data.data;
            console.log(this.products);
          } catch (error) {
            console.error('获取商品列表失败:', error);
          }
        },
        decreaseQuantity(product) {
          if (product.quantity > 1) {
            product.quantity--;
          }
        },
        increaseQuantity(product) {
          if (product.quantity < product.stock) {
            product.quantity++;
          }
        },
        async addToCart(productId, quantity) {
          try {
            // 先获取当前购物车数据
            const cartResponse = await axiosInstance.get('/cart/list');
            const cartItems = cartResponse.data.data;

            // 检查商品是否已经在购物车中
            const existingItem = cartItems.find(item => item.productId === productId);

            if (existingItem) {
                // 如果存在，更新数量
                const newQuantity = existingItem.quantity + quantity;
                await axiosInstance.put(`/cart/quantity?cartId=${existingItem.cartId}&quantity=${newQuantity}`);
            } else {
                // 如果不存在，新增商品
                await axiosInstance.post(`/cart/add?productId=${productId}&quantity=${quantity}`);
            }

            this.cartCount += quantity;
            alert('已加入购物车');
          } catch (error) {
            console.error('加入购物车失败:', error);
          }
        },
        async searchProducts() {
          try {
            const response = await axiosInstance.get(`/product/search?keyword=${this.keyword}`);
            this.products = response.data.data;
            console.log(response);

          } catch (error) {
            console.error('搜索失败:', error);
          }
        },
        async addToCart(productId) {
          try {
            await axiosInstance.post(`/cart/add?productId=${productId}`);
            this.cartCount++; // 增加购物车数量
            alert('已加入购物车');
          } catch (error) {
            console.error('加入购物车失败:', error);
          }
        },
        async toggleLike(productId) {
            try {
                const response = await axiosInstance.post(`/like/toggle/${productId}`);
                if (response.data.data) {
                    alert('已点赞');
                } else {
                    alert('已取消点赞');
                }
            } catch (error) {
                console.error('点赞失败:', error);
                alert('点赞失败: ' + error.response?.data?.message || error.message);
            }
        }
      }
    },);

  </script>
</body>
</html>